package com.ry.zk.client;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

public class ZookeeperClient {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    public String ADDRESS = "127.0.0.1:2181";
    public int TIMEOUT    = 5000;
    private ZooKeeper zooKeeper;

    public ZookeeperClient(){
        init();
    }

    public ZookeeperClient(String address){
        this.ADDRESS = address;
        init();
    }

    private void init(){
        try {
            zooKeeper = new ZooKeeper(ADDRESS, TIMEOUT, new ClientWatcher());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ClientWatcher implements Watcher{
        public void process(WatchedEvent event) {
            System.out.println("触发事件 event:"+event);
//            if(Event.KeeperState.SyncConnected == event.getState())
//                countDownLatch.countDown();
        }
    }

    public ZooKeeper getZooKeeper() {
        return zooKeeper;
    }

    /**
     * czxid 创建该节点的事物ID
     *
     * ctime 创建该节点的时间
     *
     * mZxid 更新该节点的事物ID
     *
     * mtime 更新该节点的时间
     *
     * pZxid 操作当前节点的子节点列表的事物ID(这种操作包含增加子节点，删除子节点)
     *
     * cversion 当前节点的子节点版本号
     *
     * dataVersion 当前节点的数据版本号
     *
     * aclVersion 当前节点的acl权限版本号
     *
     * ephemeralowner 当前节点的如果是临时节点，该属性是临时节点的事物ID
     *
     * dataLength 当前节点的d的数据长度
     *
     * numchildren 当前节点的子节点个数
     */
    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZookeeperClient().getZooKeeper();
        System.out.println("------------"+zooKeeper.getState());

        try {
//            countDownLatch.await();
            //exists可以监控子目录的节点变化,以及当前节点的变化【创建，删除】
            System.out.println("目录节点状态：["+zooKeeper.exists("/wjj",true)+"]");
            String nodeId = zooKeeper.create("/wjj/cwz", "jj".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("---create:"+nodeId);
            System.out.println(zooKeeper.getChildren("/wjj", false));


//            zooKeeper.create("/wjj/hh", "jj".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//            System.out.println("-----new node id:"+nodeId);
//            System.out.println(new String(zooKeeper.getData("/wjj/cwz",true,null)));
//            zooKeeper.delete("/wjj/wcr0000000002",-1);
//            zooKeeper.delete("/wjj/cwz0000000001",-1);
//            zooKeeper.delete("/wjj/wcr",-1);
//            zooKeeper.delete("/wjj",-1);

//            zooKeeper.getData()
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread.sleep(3000);
        System.out.println("zookeeper session established");
    }
}
